const Router = require('koa-router')
const passport = require('koa-passport')
// 引入时间格式化
const formatDate = require('../../utils/dateFormat').formatDate
const router = new Router()

// 引入实例
const Announcement = require('../../models/Announcement')

// 鉴权
// passport.authenticate('jwt', { session: false })
/**
 * @route GET
 * @desc 测试接口地址
 * @access public
 */
router.get('/test', async ctx => {
  ctx.status = 200
  ctx.body = {
    msg: 'works'
  }
})
/**
 * @description 新增
 */
router.post('/add', async ctx => {
  const body = ctx.request.body
  if (!body.title || !body.content || !body.announcer) {
    ctx.status = 400
    ctx.body = {
      msg: '标题，内容和发布人不可为空'
    }
    return
  }
  const findResult = await Announcement.find({ title: body.title })
  if (findResult.length > 0) {
    ctx.status = 400
    ctx.body = {
      msg: '公告已存在'
    }
  } else {
    const newAnnouncement = new Announcement({
      title: body.title,
      content: body.content,
      announcer: body.announcer
    })
    await newAnnouncement
      .save()
      .then(announcement => {
        ctx.body = announcement
      })
  }
})

/**
 * @description 查找所有公告(分页)
 */
router.get('/page', async ctx => {
  const query = ctx.request.query
  let page = Number(query.page) ? Number(query.page) : 1
  let per_page = Number(query.per_page) ? Number(query.per_page) : 9999
  // 标题筛选
  let title = query.title ? new RegExp(query.title) : /[\s\S]*/
  let skip = (page - 1) * per_page
  let data = await Announcement.find({ $or: [{ title: { $regex: title } }], isDeleted: 0 }).skip(skip).limit(per_page)
  let total = await Announcement.find({ isDeleted: 0 }).countDocuments()
  ctx.status = 200
  ctx.body = {
    per_page,
    current_page: page,
    total,
    data
  }
})

/**
 * @description 修改公告
 */
router.post('/edit', async ctx => {
  let body = ctx.request.body
  const id = ctx.request.body._id
  try {
    const updateResult = await Announcement.findByIdAndUpdate(id, body)
    if (updateResult) {
      ctx.status = 200
      ctx.body = updateResult
    } else {
      ctx.status = 400
      ctx.response.status = 400
      ctx.response.message = '数据库中无该条数据'
      ctx.body = {
        msg: '修改失败'
      }
    }
  } catch {

  }
})

/**
 * @description 删除
 */
router.post('/delete', async ctx => {
  const id = ctx.request.body.id
  try {
    const updateResult = await Announcement.findByIdAndUpdate(id, { isDeleted: 1 })
    if (updateResult) {
      ctx.status = 200
      ctx.body = updateResult
    } else {
      ctx.status = 400
      ctx.response.status = 400
      ctx.body = {
        msg: '删除失败'
      }
    }
  } catch { }
})
module.exports = router.routes()